package com.xpf.shardingtabledemo.dbqueryext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * @Author xpf
 * @Date 2023/9/22 16:45
 * @Version 1.0
 */
@Component
public class CreateTableExecutor {
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public CreateTableExecutor(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void createTable() {

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 自动往后建6个月
        for (int i = 0; i < 6; i++) {
            LocalDate nextMonth = currentDate.plusMonths(i + 1);
            int monthValue = nextMonth.getMonthValue();
            int year = nextMonth.getYear();
            String formattedMonth = String.format("%02d", monthValue);
            String tableName = "myLogs" + year + "_" + formattedMonth;
            String sql = "CREATE TABLE IF NOT EXISTS \"byd_crm_integration\".\"tablename\" (" +
                    "\tid SERIAL PRIMARY KEY," +
                    ");";
            sql = sql.replace("tablename", tableName);

            jdbcTemplate.execute(sql);
            System.out.println("Table created successfully.");
        }




    }
}
